let Mock = require('mockjs')
import envConf from '@/conf/env.conf.js'

// 模拟假数据
function getBooks() {
    let res = Mock.mock({
        'code': '200',
        'error_msg': '',
        'data|20': [{
            'id|+1': 1,
            'img': "@image('200x200', '#4A7BF7','#EB6901','pic')",
            'bookName': '@ctitle(3,8)',
            'author': '@cname(3,8)',
            'content': '@cparagraph()',
            'city': "@county(true)",
            'stock_num': '@integer(0,100)',//库存数量
            'marketing_start': '@datetime()',
            'marketing_stop': '@now()',
            'price': '@integer(100,2000)',//现价，单位：分
            'original_price': '@integer(100,3000)',
            'ageRange': '@integer(0,3)',
            'isCollection': '@boolean()',
            'shoppingCart': '@boolean()'
        }]
    })
    return res.data || [];
}

export const METHODS = {
    GET: 'GET',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE'
}
const globalData = getApp().globalData;

function request(params) {
    let url = params.url;
    const requestTask = uni.request({
        url,
        method: (params.method || METHODS.GET).toUpperCase(),
        data: params.data,
        success: res => {
            if (res.statusCode === 401) {
                uni.showToast({
                    title: '您没有访问权限',
                    icon: 'none',
                    duration: 2000
                })
                return
            } else if (res.statusCode === 404) {
                uni.showToast({
                    title: '您访问的接口不存在',
                    icon: 'none',
                    duration: 2000
                })
                return
            } else if (res.statusCode !== 200 && res.statusCode !== 304) {
                // 服务端明确错误
                uni.showToast({
                    title: '服务器请求失败',
                    icon: 'none',
                    duration: 2000,
                });
                return;
            }
            if (params.success) {
                params.success(res.data);
            }
        },
        fail: res => {
            if (params.fail) {
                params.fail(res);
            } else {
                uni.showToast({
                    title: '服务器请求失败：' + JSON.stringify(res),
                    icon: 'none',
                    duration: 2000,
                });
            }
        },
        complete: res => {
            if (params.complete) {
                params.complete(res);
            }
        },
        header: {
            deviceType: 'xcx',
            appId: globalData.appId,
            // clientId : clientId,
            // userId : userId,
        },
    })
    return requestTask;
}

export default {
    getBooks,
    request
}